interface DataItem {
  id: number
  label: string
  children?: DataItem[]
}

interface MapItem extends DataItem {
  pid?: number
  isLeftNode: boolean
}

const setMenuMap = (
  data: DataItem[],
  pid?: number,
  map = new Map<number, MapItem>()
) => {
  if (!Array.isArray(data)) return map

  data.forEach((item) => {
    map.set(item.id, {
      ...item,
      pid,
      isLeftNode: !item.children
    })
    if (item.children) {
      setMenuMap(item.children, item.id, map)
    }
  })

  return map
}

export const useMenuHandler = (menuData: DataItem[]) => {
  const menuMap = setMenuMap(menuData)

  return {
    // ids => ids + parent.id
    handler(ids: number[]) {
      const queue = [...ids]
      const _ids = new Set()

      while (queue.length) {
        const id = queue.shift()!
        const node = menuMap.get(id)
        if (node) {
          _ids.add(node.id)

          if (node.pid) {
            queue.push(node.pid)
          }
        }
      }

      return [..._ids.values()]
    },
    // ids => leftNode.id
    getHandler(ids: number[]) {
      return ids.filter((v) => menuMap.get(v)?.isLeftNode)
    }
  }
}
